package com.ermao.mymes.service.api.impl.action;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.StrUtil;
import com.ermao.mymes.service.api.domain.MessageParam;
import com.ermao.mymes.service.api.impl.domain.SendTaskModel;
import com.ermao.mymes.common.enums.RespStatusEnum;
import com.ermao.mymes.support.pipeline.BusinessProcess;
import com.ermao.mymes.support.pipeline.ProcessContext;
import com.ermao.mymes.common.vo.BasicResultVO;
import lombok.extern.slf4j.Slf4j;

import java.util.List;
import java.util.stream.Collectors;

/**
 * 使用 AssembleAction 进行参数拼装之后进行参数拼装结果的检查
 * 如果 messageTemplateId 或者 messageParamList 为空的话就结束责任链的执行
 * @author Ermao
 * Date: 2022/5/7 19:13
 */
@Slf4j
public class PreParamCheckAction implements BusinessProcess {
	@Override
	public void process(ProcessContext context) {
		SendTaskModel sendTaskModel = (SendTaskModel) context.getProcessModel();

		Long messageTemplateId = sendTaskModel.getMessageTemplateId();
		List<MessageParam> messageParamList = sendTaskModel.getMessageParamList();

		// 没有传入 消息模板Id 或者 messageParam
		if (messageTemplateId == null || CollUtil.isEmpty(messageParamList)) {
			context.setNeedBreak(true).setResponse(BasicResultVO.fail(RespStatusEnum.CLIENT_BAD_PARAMETERS));
			return;
		}

		// 过滤 receiver=null 的messageParam
		List<MessageParam> resultMessageParamList = messageParamList.stream()
				.filter(messageParam -> !StrUtil.isBlank(messageParam.getReceiver()))
				.collect(Collectors.toList());
		if (CollUtil.isEmpty(resultMessageParamList)) {
			context.setNeedBreak(true).setResponse(BasicResultVO.fail(RespStatusEnum.CLIENT_BAD_PARAMETERS));
			return;
		}

		sendTaskModel.setMessageParamList(resultMessageParamList);
	}
}
